using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerctrl : MonoBehaviour
{
    Rigidbody2D body;
    public float moveforce = 100f;
    public float maxspeed = 5f;
    [HideInInspector]
    public bool faceright = true;
    Transform mgroundcheck;
    bool begrounded = false;
    [HideInInspector]
    public bool bejump = false;
    public float jumpforce = 200f;

    private Animator anim;
    // Start is called before the first frame update
    void Start()
    {
        body = GetComponent<Rigidbody2D>();

    }

    private void Awake()
    {
        mgroundcheck = transform.Find("groundcheck");
        anim = GetComponent<Animator>();
    }
    private void FixedUpdate()
    {
        float h = Input.GetAxis("Horizontal");
        body.AddForce(Vector2.right*h*moveforce);
        anim.SetFloat("speed", Mathf.Abs(h));
        if (Mathf.Abs(body.velocity.x) > maxspeed)
        {
            body.velocity = new Vector2(Mathf.Sign(body.velocity.x) * maxspeed, body.velocity.y);
        }
        if(h<0 &&faceright)
        {
            flip();
        }
        else if(h>0 && !faceright)
        {
            flip();
        }

        if(bejump)
        {
            anim.SetTrigger("jump");
            body.AddForce(new Vector2(0,jumpforce));
            bejump = false;
        }
    }   

    void flip()
    {
        Vector3 localScale = transform.localScale;
        localScale.x *= -1;
        transform.localScale = localScale;
        faceright = !faceright;
    }
    // Update is called once per frame
    void Update()
    {
        begrounded =  Physics2D.Linecast(transform.position, mgroundcheck.position,
                            1 << LayerMask.NameToLayer("Ground"));
        if (begrounded && Input.GetButtonDown("Jump"))
        {
            bejump = true;
        }
    }
}
